<template>
  <div>
    <div class="amap-page-container">
      <!-- 搜索框 -->
      <el-amap-search-box
        v-if="edit"
        class="search-box"
        :search-option="searchOption"
        :on-search-result="onSearchResult"
      ></el-amap-search-box>
      <!-- 地图 -->
      <el-amap
        ref="map"
        vid="amapDemo"
        :amap-manager="amapManager"
        :center="center"
        :zoom="zoom"
        :events="mapInfo.events"
        :plugin="mapInfo.plugin"
        class="amap-demo"
      >
        <!-- 位置名称显示 -->
        <!-- <el-amap-text
          v-for="(marker, index) in point"
          :key="'text' + index"
          :text="marker.text"
          :offset="marker.offset"
          :position="marker.position"
        /> -->
      </el-amap>
    </div>
  </div>
</template>

<script>
import { AMapManager } from "vue-amap";
import GPS from "./convertGps";
let amapManager = new AMapManager();
export default {
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    edit: {
      type: Boolean,
      default: true,
      require: false,
    },
    // 0:高德坐标 1:gps坐标
    type: {
      type: Number,
      default: 0,
      require: false,
    },
    initStart: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const self = this;
    return {
      address: null,
      amapManager,
      marker: "",
      searchOption: {
        city: "",
        citylimit: false, // 不限制搜索范围搜索，比如想全国搜索
      },
      zoom: 15,
      lng: "",
      lat: "",
      center: [120.069898, 30.322001],
      // 输出的点位
      point: [],
      loaded: false,
      mapInfo: {
        events: {
          init: (o) => {
            o.getCity((result) => {
              let par =
                document.getElementsByClassName("search-box-wrapper")[0];
              par.firstChild.setAttribute(
                "placeholder",
                "您可以在这里输入要搜索的地址"
              );
              //todo 定位到搜索位置
              this.searchOption.city = result.city;
            });
          },
          moveend: () => {},
          zoomchange: () => {},
          click: (e) => {
            if (!self.edit) {
              return false;
            }
            self.point = [e.lnglat.getLng(), e.lnglat.getLat()];
            // let { lng, lat } = e.lnglat;
            // self.lng = lng;
            // self.lat = lat;
            // // 这里通过高德 SDK 完成。
            // var geocoder = new AMap.Geocoder({
            //   radius: 1000,
            //   extensions: "all",
            // });
            // geocoder.getAddress([lng, lat], function (status, result) {
            //   if (status === "complete" && result.info === "OK") {
            //     if (result && result.regeocode) {
            //       self.address = result.regeocode.formattedAddress;
            //       // self.point = [];
            //       const obj = {
            //         position: [lng, lat],
            //         text: result.regeocode.formattedAddress,
            //         offset: [0, 30],
            //       };
            //       self.point.push(obj);
            //       self.submit();
            //       self.$nextTick();
            //     }
            //   }
            // });
          },
        },
        // 一些工具插件
        plugin: [
          // {
          //   // 定位
          //   pName: "GeoloCation",
          //   events: {
          //     init(o) {
          //       // o 是高德地图定位插件实例
          //       o.getCurrentPosition((status, result) => {
          //         // console.log(JSON.stringify(result));
          //         if (result && result.position) {
          //           self.lng = result.position.lng;
          //           self.lat = result.position.lat;
          //           self.address = result.formattedAddress;
          //           self.center = [self.lng, self.lat];
          //           let o = amapManager.getMap();
          //           if (!self.marker) {
          //             self.marker = new AMap.Marker({
          //               position: self.center,
          //             });
          //             self.marker.setMap(o);
          //           }
          //           self.marker.setPosition(self.center);
          //         } else {
          //           self.$message.error("位置信息，获取失败！");
          //         }
          //       });
          //     },
          //   },
          // },
          // {
          //   // 工具栏
          //   pName: "ToolBar",
          //   // locate:true, // 定位
          //   // direction:true, // 方向键盘是否可见
          //   liteStyle: true, // 精简模式
          //   // position:"RB", // 位置，默认为LT 代表 左上方
          // },
          // {
          //   // 地图类型
          //   pName: "MapType",
          //   defaultType: 0,
          //   events: {
          //     init(o) {},
          //   },
          // },
          // { pName: "OverView", isOpen: true },
          // "Scale",
          // "ToolBar",
          // "CircleEditor",
        ],
      },

      mouseTool: null,
      fenceForm: {
        coordinate: [],
        fenceData: {},
      },
      mousetoolType: null,
    };
  },
  watch: {
    data: {
      handler(val) {
        if (val) {
          this.setLatLng();
        }
      },
      deep: true,
    },
    initStart: {
      handler(val) {
        if (val) {
          setTimeout(() => {
            this.addFence("polygon");
          }, 200);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    addFence(type) {
      let fenceData = {};
      this.mousetoolType = type;
      let _this = this;
      let map = amapManager.getMap();
      if (this.fenceForm.coordinate.length > 0) {
        this.$Message.error("围栏已存在!");
        return;
      }
      if (this.mousetoolType) {
        map.remove(this.mousetoolType);
      }
      map.plugin(["AMap.MouseTool"], function () {
        let mouseTool = new AMap.MouseTool(map);
        _this.mouseTool = mouseTool;
        //添加事件
        if (type === "polygon") {
          let map = amapManager.getMap();
          mouseTool.polygon();
          AMap.event.addListener(mouseTool, "draw", function (e) {
            _this.fenceForm.coordinate = [];
            let path = e.obj.getPath();
            path.forEach((e) => {
              _this.fenceForm.coordinate.push([e.getLng(), e.getLat()]);
            });
            mouseTool.close(false);
            // console.log('lujing', e.obj.getPath()) //获取路径/范围
            let fenceData = [];
            let fenceDataItem = {};
            e.obj.getPath().forEach((item) => {
              fenceDataItem = {
                lng: item.lng + "",
                lat: item.lat + "",
              };
              fenceData.push(fenceDataItem);
            });
            _this.fenceForm.fenceData = fenceData;
            // 清除原来的
            map.clearMap();
            // 引入多边形编辑器插件
            let paths = _this.fenceForm.coordinate;
            var polygon = new AMap.Polygon({
              path: paths,
              strokeColor: "#FF33FF",
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              fillColor: "#1791fc",
              zIndex: 50,
              bubble: true,
            });
            map.add([polygon]);
            map.setFitView();
            map.plugin(["AMap.PolyEditor"], function () {
              // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
              var polyEditor = new AMap.PolyEditor(map, polygon);
              // polyEditor.open()
              // 开启编辑模式
              polyEditor.open();
              polyEditor.on("adjust", function (event) {
                log.info("触发事件：adjust");
                let path = event.target.w.path;
                let pathData = {};
                let data = [];
                path.forEach((item) => {
                  for (let key in item) {
                    if (key === "lng") {
                      pathData.lng = item[key] + "";
                    } else if (key === "lat") {
                      pathData.lat = item[key] + "";
                    }
                  }
                  data.push(pathData);
                  pathData = {};
                });
                _this.fenceForm.fenceData = data;
              });
            });
            _this.$emit("result", _this.fenceForm);
          });
        }
      });
    },
    submit() {
      // this.$emit("result", this.point);
    },
    setLatLng() {
      if (this.data.length <= 0) {
        return false;
      }
      let that = this;
      let o = amapManager.getMap();
      let info = { lon: that.data[0].lng, lat: that.data[0].lat };
      if (this.type === 1) {
        info = GPS.gcj_encrypt(that.data[0].lat, that.data[0].lng);
      }
      // that.center = [info.lon, info.lat];
      if (!that.marker) {
        that.marker = new AMap.Marker({
          position: [info.lon, info.lat],
        });
        that.marker.setMap(o);
      }
      that.data.forEach((item, index) => {
        let data =
          this.type === 1
            ? GPS.gcj_encrypt(item.lat, item.lng)
            : { lon: item.lng, lat: item.lat };
        that.marker.setPosition([data.lon, data.lat]);
        if (!that.edit) {
          // that.polyline.path.push([data.lon, data.lat]);
        }
      });
    },
    onSearchResult(pois) {
      if (pois.length > 0) {
        let { lng, lat, name, location, address } = pois[0];
        //?显示
        // this.point = [];
        const obj = {
          position: [lng, lat],
          text: address + name,
          offset: [0, 30],
        };
        this.point.push(obj);
        this.address = address + name;
        let center = [lng, lat];
        this.lng = lng;
        this.lat = lat;
        this.center = [lng, lat];
        let o = amapManager.getMap();
        if (!this.marker) {
          this.marker = new AMap.Marker({
            position: center,
          });
          this.marker.setMap(o);
        }
        this.marker.setPosition(center);
        // this.polyline.path = [];
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.amap-demo {
  height: 400px;
}

.search-box {
  height: 40px;
  position: absolute;
  top: 10px;
  right: 20px;
}
.amap-page-container {
  position: relative;
}
</style>
>
